package com.cuit.controller;

import com.cuit.common.Result;
import com.cuit.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@RestController
@RequestMapping("/api/upload")
public class UploadController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping
    public Result uploadAvatar(@RequestParam(value = "file",required = false) MultipartFile file) {
        if(file.isEmpty()) {
            return Result.error();
        }
        String OriginalFilename = file.getOriginalFilename();
        String fileName = System.currentTimeMillis() + "." + OriginalFilename.substring(OriginalFilename.lastIndexOf(".") + 1);
        String path = "D:\\HuaweiMoveData\\Users\\ALvetX\\Desktop\\bishe\\bishe-vue\\src\\assets\\images\\";
        File dest = new File(path + fileName);
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }

        try {
            file.transferTo(dest);
            userMapper.updateAvatar(1L,fileName);
            return Result.success(fileName);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error();
        }
    }
}